﻿@page "/DesiginerPro"
<CascadingValue Value="FunctionPage.MainPage" Name="MainPage" IsFixed="false">

    <div style="height:100%;width:100%;display:flex">
        @if (isdesigner)
        {
            <div class="dmain-left" style="width:20%">
                <Tab>
                    <TabItem Text="菜单管理">
                        <Table TItem="FunctionPage" TableSize="TableSize.Compact" IsPagination="true"
                               PageItemsSource="new int[]{20,10,50}"
                               ShowExtendButtons="true" ShowExtendEditButton="true"
                               ShowExtendDeleteButton="false"
                               ShowToolbar="true" ShowEditButton="false" ShowAddButton="false"
                               ShowDeleteButton="false"
                               ShowSearch="true" ShowAdvancedSearch="false" ShowResetButton="false"
                               IsStriped="true" IsBordered="true" IsMultipleSelect="false"
                               AutoGenerateColumns="true"
                               ShowSkeleton="true" IsExtendButtonsInRowHeader="true"
                               ClickToSelect="true"
                               OnClickRowCallback="OnClickRowCallbackProduct"
                               OnQueryAsync="OnQueryAsync" OnDeleteAsync="OnDeleteAsync" OnSaveAsync="OnSaveAsync"
                               OnAddAsync="OnAddAsync">
                        </Table>
                    </TabItem>
                    <TabItem Text="工具箱">
                        <Collapse>
                            <CollapseItems>
                                <CollapseItem Text="普通控件" IsCollapsed="false">
                                    <WidgetBtn Icon="fa-solid fa-language" Data="WidgetType.InputText" Text="文本框"></WidgetBtn>
                                    <WidgetBtn Icon="fas fa-table" Data="WidgetType.Table" Text="表格"></WidgetBtn>
                                    <WidgetBtn Icon="fas fa-bullseye" Data="WidgetType.Bottom" Text="按钮"></WidgetBtn>
                                    <WidgetBtn Icon="far fa-check-circle" Data="WidgetType.CheckBox" Text="复选框"></WidgetBtn>
                                </CollapseItem>
                                <CollapseItem Text="容器控件">
                                    <WidgetBtn Icon="fas fa-tent-arrow-left-right" Data="WidgetType.SplitH" Text="水平分割"></WidgetBtn>
                                    <WidgetBtn Icon="fas fa-arrows-up-down" Data="WidgetType.SplitV" Text="垂直分割"></WidgetBtn>
                                    <WidgetBtn Icon="fas fa-box-archive" Data="WidgetType.Row" Text="行控件"></WidgetBtn>
                                    <WidgetBtn Icon="fas fa-toilets-portable" Data="WidgetType.Tab" Text="多页签"></WidgetBtn>
                                </CollapseItem>
                                <CollapseItem Text="图标控件">
                                    早晚会有..
                                </CollapseItem>
                                <CollapseItem Text="交互控件">
                                    早晚会有..
                                </CollapseItem>
                            </CollapseItems>
                        </Collapse>
                    </TabItem>
                    <TabItem Text="控件树">
                        <Button OnClick="TreeRefresh">刷新</Button>
                        @if (ControlTree != null)
                        {
                            <TreeView TItem="Control" Items="@ControlTree" OnTreeItemClick="@OnTreeItemClick" />
                        }
                    </TabItem>
                </Tab>
            </div>
        }

        <div class="dmain-main" style="z-index:1;width:@(isdesigner?60:80)%">
            @if (FunctionPage != null && FunctionPage.MainPage != null)
            {
                <ControlComponent Data="FunctionPage.MainPage.Controlmain" ParentData="FunctionPage.MainPage.Controlmain"></ControlComponent>
            }
            else
            {
                <span>未获取到页面,请新建或者选择一个页面</span>
            }
        </div>


        @if (true)
        {
            <div class="dmain-right" style="width:20%">
                <Tab>
                    <TabItem Text="属性管理">
                        @if (FunctionPage != null)
                        {
                            <div style="height:8%">
                                @if (FunctionPage.MainPage != null && FunctionPage.Id != 0)
                                {
                                    <Button OnClick="SaveLayout" ButtonStyle="ButtonStyle.Round" Color="Color.Success">保存</Button>
                                    <Button OnClick="CopyLayout" ButtonStyle="ButtonStyle.Round" Color="Color.Primary">复制</Button>
                                    <Button OnClick="DeleteLayout" ButtonStyle="ButtonStyle.Round" Color="Color.Warning">删除</Button>
                                }
                                <Button OnClick="NewLayout" ButtonStyle="ButtonStyle.Round" Color="Color.Info">新建</Button>
                            </div>

                        }

                        @if (FunctionPage != null && FunctionPage.MainPage != null && FunctionPage.MainPage.SelectControl != null)
                        {
                            <ControlProperties Data="FunctionPage.MainPage.SelectControl"></ControlProperties>
                        }
                    </TabItem>
                    <TabItem Text="工具箱">
                        <Button OnClick="()=>{IsShowBackdropOpen=!IsShowBackdropOpen;isdesigner=!isdesigner;}">工具箱</Button>
                    </TabItem>
                </Tab>
            </div>
        }



    </div>
    <div class="cus-drawer">

   
    <Drawer Placement="Placement.Left" @bind-IsOpen="@IsShowBackdropOpen" ShowBackdrop="false">
        <div style="width:100%;height:100%;">
            <Tab>
                <TabItem Text="工具箱">
                    <Collapse>
                        <CollapseItems>
                            <CollapseItem Text="普通控件" IsCollapsed="false">
                                <WidgetBtn Icon="fa-solid fa-language" Data="WidgetType.InputText" Text="文本框"></WidgetBtn>
                                <WidgetBtn Icon="fas fa-table" Data="WidgetType.Table" Text="表格"></WidgetBtn>
                                <WidgetBtn Icon="fas fa-bullseye" Data="WidgetType.Bottom" Text="按钮"></WidgetBtn>
                            </CollapseItem>
                            <CollapseItem Text="容器控件">
                                <WidgetBtn Icon="fas fa-tent-arrow-left-right" Data="WidgetType.SplitH" Text="水平分割"></WidgetBtn>
                                <WidgetBtn Icon="fas fa-arrows-up-down" Data="WidgetType.SplitV" Text="垂直分割"></WidgetBtn>
                                <WidgetBtn Icon="fas fa-box-archive" Data="WidgetType.Row" Text="行控件"></WidgetBtn>
                                <WidgetBtn Icon="fas fa-toilets-portable" Data="WidgetType.Tab" Text="多页签"></WidgetBtn>
                            </CollapseItem>
                            <CollapseItem Text="图标控件">
                                早晚会有..
                            </CollapseItem>
                            <CollapseItem Text="交互控件">
                                早晚会有..
                            </CollapseItem>
                        </CollapseItems>
                    </Collapse>
                </TabItem>
                <TabItem Text="控件树">
                    <Button OnClick="TreeRefresh">刷新</Button>
                    @if (ControlTree != null)
                    {
                        <TreeView TItem="Control" Items="@ControlTree" OnTreeItemClick="@OnTreeItemClick" />
                    }
                </TabItem>
            </Tab>
        </div>
    </Drawer>
    </div>
</CascadingValue>

@code {
    public bool IsShowBackdropOpen { get; set; }
    [Inject]
    [NotNull]
    private MessageService? MessageService { get; set; }
    [Inject]
    [NotNull]
    private SwalService? SwalService { get; set; }
    [Inject]
    [NotNull]
    private ToastService? ToastService { get; set; }
    [Inject]
    [NotNull]

    public ISqlSugarClient? db { get; set; }
    private List<TreeViewItem<Control>>? ControlTree { get; set; }
    public bool isdesigner { get; set; } = true;

    public FunctionPage FunctionPage { get; set; } = new();
    public List<FunctionPage>? FunctionPageList { get; set; }
    protected override void OnInitialized()
    {
        base.OnInitialized();
        // FunctionPage = new FunctionPage() { MainPage = new MainPage() };
        // FunctionPage.MainPage.StateHasChanged = StateHasChanged;
        // var json = System.Text.Json.JsonSerializer.Serialize(FunctionPage);
        return;
        // var json = System.Text.Json.JsonSerializer.Serialize(Controlmain);
        // Controlmain = System.Text.Json.JsonSerializer.Deserialize<Control>(json) ?? new Control();
    }
    private Task<QueryData<FunctionPage>> OnQueryAsync(QueryPageOptions options)
    {
        // IEnumerable<Product> items = Items;
        var items = db.Queryable<FunctionPage>().ToList();
        items = items ?? new List<FunctionPage>();
        // 过滤
        var isFiltered = false;
        if (options.Filters.Any())
        {
            // items = items.Where(options.Filters.GetFilterFunc<Product>());
            isFiltered = true;
        }

        // 排序
        var isSorted = false;
        if (!string.IsNullOrEmpty(options.SortName))
        {
            // var invoker = Foo.GetNameSortFunc();
            // items = invoker(items, options.SortName, options.SortOrder);
            isSorted = true;
        }

        // 设置记录总数
        var total = items.Count();
        // 内存分页
        items = items.Skip((options.PageIndex - 1) * options.PageItems).Take(options.PageItems).ToList();
        return Task.FromResult(new QueryData<FunctionPage>() { Items = items, TotalCount = total, IsSorted = isSorted, IsFiltered = isFiltered, IsSearch = true });
    }
    public async Task<bool> OnDeleteAsync(IEnumerable<FunctionPage> list)
    {
        await db.Deleteable<FunctionPage>(list).ExecuteCommandAsync();
        return true;
    }
    private async Task<bool> OnSaveAsync(FunctionPage item, ItemChangedType changedType)
    {
        try
        {
            switch (changedType)
            {
                case ItemChangedType.Add:
                    db.Insertable<FunctionPage>(item).ExecuteReturnSnowflakeId();
                    break;
                case ItemChangedType.Update:
                    db.Updateable(item).ExecuteCommand();
                    break;
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            var op = new SwalOption()
                {
                    Category = SwalCategory.Success,
                    Title = $"失败",
                    Content = $"失败:{ex.Message}",
                    ShowClose = true
                };
            await SwalService.Show(op);
            return false;
        }

        StateHasChanged();
        return true;
    }
    public async Task<FunctionPage> OnAddAsync()
    {
        await Task.Delay(200);
        var obj = new FunctionPage() { MainPage = new MainPage() };
        return obj;
    }
    public async Task OnClickRowCallbackProduct(FunctionPage p)
    {
        if (FunctionPage.Id != p.Id)
        {
            FunctionPage = p;
            if (FunctionPage.MainPage != null)
            {
                FunctionPage.MainPage.StateHasChanged = StateHasChanged;
            }
        }
        StateHasChanged();
        await Task.Delay(50);
    }

    public void TreeRefresh()
    {
        List<TreeViewItem<Control>> treelist = new();
        if (FunctionPage != null && FunctionPage.MainPage != null)
        {
            FunctionPage.MainPage.Controlmain.ToTree(treelist);
            ControlTree = treelist;
        }
    }
    private Task OnTreeItemClick(TreeViewItem<Control> item)
    {
        if (FunctionPage != null && FunctionPage.MainPage != null)
        {
            FunctionPage.MainPage.SelectControl = item.Value;
        }
        StateHasChanged();
        return Task.CompletedTask;
    }
    /// <summary>
    /// 保存布局
    /// </summary>
    public async Task SaveLayout()
    {
        try
        {
            await db.Updateable(FunctionPage).ExecuteCommandAsync();
            await MessageService.Show(new MessageOption()
                {
                    Content = "保存成功",
                    Icon = "fa-solid fa-circle-info",
                    Color = Color.Success
                });
        }
        catch (Exception ex)
        {
            await MessageService.Show(new MessageOption()
                {
                    Content = ex.Message,
                    Icon = "fa-solid fa-circle-info",
                    Color = Color.Warning
                });
        }
        StateHasChanged();
    }
    /// <summary>
    /// 复制布局
    /// </summary>
    public async Task CopyLayout()
    {
        try
        {
            await db.Insertable<FunctionPage>(new FunctionPage() { MainPage = FunctionPage.MainPage }).ExecuteReturnSnowflakeIdAsync();
            await MessageService.Show(new MessageOption()
                {
                    Content = "复制成功,请手动刷新左侧菜单栏",
                    Icon = "fa-solid fa-circle-info",
                    Color = Color.Success
                });
        }
        catch (Exception ex)
        {
            await MessageService.Show(new MessageOption()
                {
                    Content = ex.Message,
                    Icon = "fa-solid fa-circle-info",
                    Color = Color.Warning
                });
        }
        StateHasChanged();
    }
    public async Task DeleteLayout()
    {
        try
        {
            await db.DeleteNav<FunctionPage>(x => x.Id == FunctionPage.Id)
                   .Include(x => x.Roles, new DeleteNavOptions()
                       {
                           ManyToManyIsDeleteA = true
                       })
                   .ExecuteCommandAsync();
            await MessageService.Show(new MessageOption()
                {
                    Content = "删除成功,请手动刷新左侧菜单栏",
                    Icon = "fa-solid fa-circle-info",
                    Color = Color.Success
                });
        }
        catch (Exception ex)
        {
            await MessageService.Show(new MessageOption()
                {
                    Content = ex.Message,
                    Icon = "fa-solid fa-circle-info",
                    Color = Color.Warning
                });
        }
        StateHasChanged();
    }
    public async Task NewLayout()
    {
        try
        {
            await db.Insertable<FunctionPage>(new FunctionPage() { Name = "新建", MainPage = new MainPage() { } }).ExecuteReturnSnowflakeIdAsync();
            await MessageService.Show(new MessageOption()
                {
                    Content = "新建成功,请手动刷新左侧菜单栏",
                    Icon = "fa-solid fa-circle-info",
                    Color = Color.Success
                });
        }
        catch (Exception ex)
        {
            await MessageService.Show(new MessageOption()
                {
                    Content = ex.Message,
                    Icon = "fa-solid fa-circle-info",
                    Color = Color.Warning
                });
        }
        StateHasChanged();
    }
}
